/* 
 * File:   Application.cpp
 * Author: bd
 * 
 * Created on March 26, 2011, 1:56 PM
 */

#include "Application.hpp"
#include "Activity.hpp"
#include "DeliveryActivity.hpp"
#include "ActivityManager.hpp"
#include "Database.hpp"
#include "ShortMsgItemDao.hpp"
#include <iostream>
#include <boost/make_shared.hpp>
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "inc.hpp"

const std::string Application::CONFIG_FILENAME = "sample_config.xhtml";

Monitor<bool> Application::monitor;

Application::Application()
{
    bool live = true;
    monitor.set(live);
}

Application::Application(const Application& orig)
{
}

Application::~Application()
{
}

void Application::main()
{
    loadConfig();
    init();
    start();
}

void Application::init()
{
    google::InitGoogleLogging(config_.logFile().c_str());
    LOG(INFO) << "Application initted" << "\n";
}

void Application::loadConfig()
{
    load_configuration(CONFIG_FILENAME, config_);
}

void Application::start()
{
    loadtestdata();
    createActivities();
    std::vector<boost::shared_ptr<boost::thread> >::iterator it;
    for (it = threads_.begin(); it != threads_.end(); ++it)
    {
        (*it)->join();
    }
}

void Application::stop()
{
}

void Application::createActivities()
{

    std::vector<ControllerActivity::ControllerActivityPtr> controllerVec;
    std::vector<ControllerActivity::ControllerActivityPtr>::iterator controllerVecIt;

    std::vector<DeliveryActivity::DeliveryActivityPtr> deliveryVec;
    std::vector<DeliveryActivity::DeliveryActivityPtr>::iterator deliveryVecIt;

    deliveryVec = ActivityManager::deliveryActivities(config_, pool_);
    for (deliveryVecIt = deliveryVec.begin(); deliveryVecIt != deliveryVec.end(); ++deliveryVecIt)
    {
        LOG(INFO) << "starting : " << (**deliveryVecIt).name() << "\n";
        boost::shared_ptr<boost::thread> p(new boost::thread(**deliveryVecIt));
        threads_.push_back(p);
    }

    controllerVec = ActivityManager::controllerActivities(config_, pool_);
    for (controllerVecIt = controllerVec.begin(); controllerVecIt != controllerVec.end(); ++controllerVecIt)
    {
        LOG(INFO) << "starting : " << (**controllerVecIt).name() << "\n";
        boost::shared_ptr<boost::thread> p(new boost::thread(**controllerVecIt));
        threads_.push_back(p);
    }
}

void Application::loadtestdata()
{
    using namespace boost::posix_time;
    using namespace boost::gregorian;

    Database db(config_.dataSourceConnStr());
    ShortMsgItemDao dao(db);
    dao.loadTestData(10, 1);
}